import api from "@/api";
import { LOGIN_PAGE } from "@/config";
import type { LoginForm, SysUserVo } from "@/types";
import { removeToken, setToken } from "@/utils/auth";
import { getImageUrl } from "@/utils/image";
import { defineStore } from "pinia";
import { stringify, parse } from "zipson";

export const useUserStore = defineStore("userStore", {
  state: () => {
    return {
      login_status: false,
      token: "",
      userInfo: {} as SysUserVo,
      avatarPath: "",
    };
  },
  getters: {},
  actions: {
    login(data: LoginForm): Promise<boolean> {
      return new Promise(async (resolve, reject) => {
        const res = await api.user.login(data);
        if (res.code === 200) {
          this.token = res.data.access_token;
          this.login_status = true;
          setToken(this.token);
          resolve(true);
        }
        resolve(false);
      });
    },
    async getUserInfo() {
      try {
        const res = await api.user.getUserInfo();
        this.userInfo = res.data.user;

        if (!this.avatarPath) {
          this.avatarPath = await getImageUrl(this.userInfo.avatar);
        }
      } catch (error) {
        console.error("Failed to get user info or download avatar:", error);
      }
    },
    async logout() {
      const res = await api.user.logout();
      if (res.code === 200) {
        this.login_status = false;
        this.token = "";
        this.userInfo = {} as SysUserVo;
        this.avatarPath = "";
        removeToken();
        uni.redirectTo({
          url: LOGIN_PAGE,
        });
      }
    },
  },
  persist: {
    serializer: {
      deserialize: parse,
      serialize: stringify,
    },
    afterRestore: (ctx) => {
      console.log(`刚刚恢复完 '${ctx.store.$id}'`);
      console.log(ctx);
    },
  },
});
